package com.application.Activity;

import java.util.ArrayList;

import org.w3c.dom.Document;

import ReadWriteXML.COption;
import ReadWriteXML.CQuestion;
import ReadWriteXML.CResult;
import ReadWriteXML.CUsingQuestionList;
import ReadWriteXML.ReadXML;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.application.Adapter.MyResultDoTestAdapter;
import com.application.Adapter.MyResultDoTestAdapter.ViewOption;
import com.application.Controller.ActivityController;
import com.application.Controller.ReadWriteFileController;
import com.application.DataProvider.PartDAO;

public class FrmShowResultOfTest extends ListActivity {
	private static final View View = null;
	private ArrayAdapter<String> _arrayadaptersigngle;
	private ArrayAdapter<String> _arrayadaptermulti;
	private ArrayAdapter<String> _arrayadaptertrueflase;
	private static ArrayList<ViewOption> _arrayWork;
	private static MyResultDoTestAdapter _arrayAdapter;


	private CUsingQuestionList _tests;
	static int _countQuestion = 0;
	static int _questionIndex = 0;// thu tu cua cau hoi hien tai tre arr cau hoi
	static ArrayList<Integer> _posAnswer = new ArrayList<Integer>();
	static private ListView listView;
	static private EditText _edtResultWriteQuestion;
	private TextView _txtNumberQuestion;
	private TextView _txtTitle;
	private TextView _txtContent;
	static private CQuestion _question;
	static private Document _doc;
	static private String _fNameQues = "";
	static private String _pathQues = "";
	static private CResult _result;
	static private ArrayList<Object> _answer;
	static private int _status;
	static private Context _cont;
	ArrayList<String> optionList = new ArrayList<String>();
	Handler h = new Handler();
	Runnable _r;

	// CheckedTextView _ctv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.frm_dotest);

		listView = getListView();
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);

		/* chú thích ý nghĩa các biến: */
		final ImageButton btnNext = (ImageButton) findViewById(R.id.dotest_btnnext);
		final ImageButton btnBack = (ImageButton) findViewById(R.id.dotest_btnback);
		_edtResultWriteQuestion = (EditText) findViewById(R.id.dotest_edtanswer);
		Button btnFeedback = (Button) findViewById(R.id.dotest_btnfinish);
		_txtTitle = (TextView)findViewById(R.id.dotest_txttitle);
		_txtContent = (TextView)findViewById(R.id.dotest_txtquestion);
		btnFeedback.setVisibility(android.view.View.INVISIBLE);
		_edtResultWriteQuestion.setEnabled(false);
		listView.setEnabled(false);
		listView.setItemsCanFocus(true);

		_arrayWork = new ArrayList<ViewOption>();
		_cont = this;
		_pathQues = ReadWriteFileController.DIRECTORYTESTCONTENT+_fNameQues +".xml";

		PartDAO pDao = new PartDAO(null);

		Log.d("PEERDROID", "sau _pathQues: " + _pathQues);
		_doc = ReadXML.BuildXML(_pathQues);
		if (_doc != null) {
			_tests = ReadXML.ReadReceive(_doc);
			_txtNumberQuestion = (TextView) findViewById(R.id.dotest_numberquestion);

			_countQuestion = ReadXML.readCount(_doc);// so luong cau hoi cua bai tap
			_questionIndex = 0;
			_question = ReadXML.readQuestion(_doc, _questionIndex);// lay ra cau hoi tai vi tri thu k
			_result = ReadXML.readResult(_doc, _question.get_idQuestion(),_question.get_type());
			if(_status == 3)//xem đáp án
			{
				_txtTitle.setText("Đáp án " + _tests.get_title() + " chủ đề " + pDao.getName(_tests.get_idPart()));
				_answer = ReadXML.ReadResultTest(_doc, _question.get_idQuestion(), _question.get_type());
				ShowQuesion(_question, _result, _answer);
			}
			if(_status == 2)//xem bài làm
			{
				_txtTitle.setText(_tests.get_title() + " chủ đề " + pDao.getName(_tests.get_idPart()));
				ShowQuesion(_question, _result);
			}
			_txtNumberQuestion.setText("Câu " + Integer.toString(_questionIndex + 1)+ "/" + _countQuestion);

			if(_countQuestion == 1)//chỉ có 1 câu hỏi
			{
				//				Log.d("PEERDROID","count question 1");
				btnBack.setEnabled(false);
				btnNext.setEnabled(false);

			}
			else{
				Log.d("PEERDROID","count khac 1");
				btnBack.setEnabled(false);
			}

			// bat su kien click button next
			btnNext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					btnBack.setEnabled(true);
					if (_questionIndex < _countQuestion - 1) {
						if (_questionIndex < 0) {
							_questionIndex = 0;
						}
						// set data current
						// load next data
						_questionIndex = _questionIndex + 1;
						_question = ReadXML.readQuestion(_doc, _questionIndex);
						_result = ReadXML.readResult(_doc,_question.get_idQuestion(),_question.get_type());
						if(_status == 3)//xem đáp án
						{
							_answer = ReadXML.ReadResultTest(_doc, _question.get_idQuestion(), _question.get_type());
							ShowQuesion(_question, _result, _answer);
						}
						if(_status == 2)//xem bài làm
							ShowQuesion(_question, _result);
						_txtNumberQuestion.setText("Câu "+ Integer.toString(_questionIndex + 1) + "/" + _countQuestion);
					}
					if (_questionIndex >= _countQuestion - 1) {
						btnNext.setEnabled(false);
					}
				}
			});

			// bat su kien click button back
			btnBack.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					btnNext.setEnabled(true);
					if (_questionIndex > 0) {
						if (_questionIndex == _countQuestion) {
							_questionIndex = _questionIndex - 1;
						}
						_questionIndex = _questionIndex - 1;
						// set data current

						// load back data
						_question = ReadXML.readQuestion(_doc, _questionIndex);
						_result = ReadXML.readResult(_doc,_question.get_idQuestion(),_question.get_type());
						if(_status == 3)//xem đáp án
						{
							_answer = ReadXML.ReadResultTest(_doc, _question.get_idQuestion(), _question.get_type());
							ShowQuesion(_question, _result, _answer);
						}
						if(_status == 2)//xem bài làm
							ShowQuesion(_question, _result);
						_txtNumberQuestion.setText("Câu "+ Integer.toString(_questionIndex + 1) + "/" + _countQuestion);
					}
					if (_questionIndex <= 0) {
						// btnBack.setVisibility(0);
						btnBack.setEnabled(false);
					}
				}

			});

		}

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("PEERDROID","vao onstart show result of test");
		//ActivityController.setPeerActivity(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//ActivityController.setPeerActivity(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//		ShowSubjectList();	
		Log.d("PEERDROID", "vao resume");
	//	ActivityController.setPeerActivity(this);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private ArrayList<Integer> getPosAnswer(ArrayList<COption> optList, ArrayList<Object> id)
	{
		ArrayList<Integer> arrPos = new ArrayList<Integer>();
		int i = 0;
		for (COption o : optList) {
			for(Object index : id)
				if (o.get_idDetail() == Integer.valueOf(index.toString()))
				{
					arrPos.add(i);
					break;
				}
			i++;
		}
		return arrPos;
	}
	private int getPos(ArrayList<COption> optList, int id) {
		int index = -1;
		int i = 0;
		for (COption o : optList) {
			if (o.get_idDetail() == id)
				index = i;
			i++;
		}
		return index;
	}


	// ham lay danh sach cau tra loi cua cau hoi multichoice
	private ArrayList<Integer> getPosMultiChoice(ArrayList<COption> optList,
			ArrayList<String> id) {
		ArrayList<Integer> arrIndex = new ArrayList<Integer>();
		for (int j = 0; j < id.size(); j++) {
			int temp = getPos(optList, Integer.parseInt(id.get(j)));
			arrIndex.add(temp);
		}
		return arrIndex;
	}

	private void ShowQuesion(CQuestion question, CResult result, ArrayList<Object> answer) {
		Log.d("PEERDROID","Da vao ShowQuestion");
		_txtContent.setText(_tests.get_questionList().get(_questionIndex).get_content());
		_arrayWork.clear();
		try {
			int n = question.get_listOption().size();
			for(int i=0;i<n;i++)
			{
				ViewOption view;
				String sCont = question.get_listOption().get(i).get_content();
				int idOpt = question.get_listOption().get(i).get_idDetail();
				int type;
				if(question.get_type() == 2)
				{
					type = 2;
				}
				else
				{
					type = 1;
				}
				int res = testResult(question.get_listOption().get(i), result, answer);
				view=new ViewOption(idOpt,type,res, sCont);
				_arrayWork.add(view);
			}
			if(question.get_type() == 3)//true false
			{

			}

			setListAdapter();
		} catch (android.database.SQLException e) {
			Log.d("PEERDROID", "Query error!");
		}
	}

	public static void setListAdapter() {
		Log.d("PEERDROID","set list adapter");
		_arrayAdapter=new MyResultDoTestAdapter(_cont,R.layout.row_resultdotest,_arrayWork);
		listView.setAdapter(_arrayAdapter);

	}
	private int testResult(COption option, CResult result, ArrayList<Object> answer)
	{
		int kq = 0;
		Log.d("PEERDROID", "kq: " + kq);
		Log.d("PEERDROID", "option" + option.get_content());
		Log.d("PEERDROID", "option id: " + option.get_idDetail());
		Log.d("PEERDROID", "result" + result.getChoice());
		Log.d("PEERDROID", "answer" + answer);
		switch(result.getType())
		{
		case 1://single choice
		{
			Log.d("PEERDROID", "single");
			//kiểm tra dòng đó có được làm hay ko
			if(option.get_idDetail() == Integer.valueOf(result.getChoice().get(0)))
			{
				Log.d("PEERDROID", "press" );
				//kiểm tra làm đúng hay sai tại dòng
				if(Integer.valueOf(result.getChoice().get(0)) == Integer.valueOf(answer.get(0).toString()))
				{
					Log.d("PEERDROID", "right" );
					kq = 2;
				}
				else
				{
					Log.d("PEERDROID", "wrong" );
					kq = 1;
				}
			}
			else//dòng ko được chọn
			{
				Log.d("PEERDROID", "not press" );
				//kiểm tra dòng đó có phải là đáp án đúng hay ko
				if(option.get_idDetail() == Integer.valueOf(answer.get(0).toString()))
				{
					Log.d("PEERDROID", "not pres - right" );
					kq = 3;
				}
			}
			break;
		}
		case 2://multi choice
		{
			//kiểm tra dòng đó có được làm hay ko
			for(int j = 0; j < result.getChoice().size(); j++)
				if(option.get_idDetail() == Integer.valueOf(result.getChoice().get(j)))
				{
					//kiểm tra làm đúng hay sai tại dòng
					for(int i = 0; i < answer.size(); i++)
						if(Integer.valueOf(result.getChoice().get(j)) == Integer.valueOf(answer.get(i).toString()))
						{
							kq = 2;
							break;
						}
						else
							kq = 1;
				}
				else//dòng ko được chọn
				{
					//kiểm tra dòng đó có phải là đáp án đúng hay ko
					for(int i = 0; i < answer.size(); i++)
						if(option.get_idDetail() == Integer.valueOf(answer.get(i).toString()))
							kq = 3;
				}
			break;
		}
		case 3://true false
		{
			//kiểm tra dòng đó có được làm hay ko
			if(Integer.valueOf(option.get_content()) == Integer.valueOf(result.getChoice().get(0)))
			{
				//kiểm tra làm đúng hay sai tại dòng
				if(Integer.valueOf(result.getChoice().get(0)) == Integer.valueOf(answer.get(0).toString()))
				{
					kq = 2;
				}
				else
					kq = 1;
			}
			else//dòng ko được chọn
			{
				//kiểm tra dòng đó có phải là đáp án đúng hay ko
				if(Integer.valueOf(option.get_content()) == Integer.valueOf(answer.get(0).toString()))
					kq = 3;
			}
			break;
		}
		}

		Log.d("PEERDROID", "return kq: " +kq );
		return kq;
	}

	private void ShowQuesion(CQuestion question, CResult result) {
		Log.d("PEERDROID", "show question 1");
		TextView txtcauhoi = (TextView) findViewById(R.id.dotest_txtquestion);
		txtcauhoi.setText(question.get_content().toString());
		int type = question.get_type();
		switch (type) {
		case 1: // single choice
		{
			optionList.clear();

			listView.setEnabled(true);
			listView.setVisibility(android.view.View.VISIBLE);
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			//			listView.getCheckedItemPosition();

			int n = question.get_listOption().size();
			// lay noi dung
			for (int i = 0; i < n; i++) {
				optionList.add(question.get_listOption().get(i).get_content());
			}

			// hien thi noi dung
			_arrayadaptersigngle = new ArrayAdapter<String>(this,
					R.layout.listrow_singlechoice, optionList);
			listView.setAdapter(_arrayadaptersigngle);

			// lay gia tri khoi tao:
			if (result != null) {
				int pos = getPos(question.get_listOption(),
						Integer.valueOf(result.getChoice().get(0)));
				// set gia tri cho radio button
				listView.setItemChecked(pos, true);

			}
			// to mau dap an dung.
			listView.setFocusableInTouchMode(true);	
			break;
		}
		case 2: // multi choice
		{
			optionList.clear();
			int n = question.get_listOption().size();

			listView.setEnabled(true);
			listView.setVisibility(android.view.View.VISIBLE);
			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			//			listView.getCheckedItemPosition();
			// lay noi dung
			for (int i = 0; i < n; i++) {
				optionList.add(question.get_listOption().get(i).get_content());
				// _arrayadaptermulti.notifyDataSetInvalidated();
				// _arrayadaptermulti.notifyDataSetChanged();
			}

			_arrayadaptermulti = new ArrayAdapter<String>(this,
					R.layout.listrow_multichoice, optionList);
			listView.setAdapter(_arrayadaptermulti);

			// hien thi noi dung:

			// lay gia tri khoi tao:
			if (result != null) {
				ArrayList<Integer> pos = getPosMultiChoice(
						question.get_listOption(), result.getChoice());
				for (int i = 0; i < pos.size(); i++) {
					listView.setItemChecked(pos.get(i), true);
				}

			}
			break;
		}
		case 3: // true false
		{
			optionList.clear();
			listView.setEnabled(true);
			listView.setVisibility(android.view.View.VISIBLE);
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			listView.getCheckedItemPosition();

			String[] temp = { "True", "False" };
			for (int i = 0; i < 2; i++) {
				optionList.add(temp[i]);
				// _arrayadaptertrueflase.notifyDataSetInvalidated();
				// _arrayadaptertrueflase.notifyDataSetChanged();
			}
			// hien thi noi dung
			_arrayadaptertrueflase = new ArrayAdapter<String>(this,
					R.layout.listrow_truefalse, optionList);
			listView.setAdapter(_arrayadaptertrueflase);

			// lay gia tri khoi tao:
			if (result != null) {
				if (Integer.valueOf(result.getChoice().get(0)) == 1) {
					listView.setItemChecked(0, true);
				} else {
					listView.setItemChecked(1, true);
				}
			}
			// to mau dap an dung. 0: vi tri dap an dung
			break;
		}
		case 4: // noi cot
		{
			break;
		}
		case 5: // writequest
		{
			EditText edtcautraloi = (EditText) findViewById(R.id.dotest_edtanswer);
			edtcautraloi.setEnabled(true);
			edtcautraloi.setVisibility(1);
			listView.setEnabled(false);
			listView.setVisibility(android.view.View.GONE);
			// lay gia tri khoi tao:
			if (result != null) {
				_edtResultWriteQuestion.setText(result.getChoice().get(0));

			}
			break;
		}
		}
	}

	public static void set_fNameQues(String _fNameQues) {
		FrmShowResultOfTest._fNameQues = _fNameQues;
	}

	public static String get_fNameQues() {
		return _fNameQues;
	}

	public static void set_status(int _status) {
		FrmShowResultOfTest._status = _status;
	}

	public static int get_status() {
		return _status;
	}

}
